package com.archerdu.base.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Writer;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.archerdu.commons.util.FileUtil;
import com.archerdu.commons.util.ImgUtil;

/**
 * CKEditor 上传控制器
 * 
 * @projectName springDemo
 * @description CKEditor 上传控制器
 * @author archer du
 * @createDate 2013年9月27日 下午5:28:54
 * @updateUser dxf
 * @updateDate 2013年9月27日 下午5:28:54
 * @updateRemark 新建
 * @version 0.0.1
 */
@Controller
@RequestMapping(value = "/common")
public class CKeditorUploadController
        extends BaseController {
    
    private static final long serialVersionUID = 4763069862840822079L;
    
    @RequestMapping(value = "/CKeditorUpload")
    public void upload(HttpServletRequest request, @RequestParam("CKEditorFuncNum") String CKEditorFuncNum,
            @RequestParam("upload") MultipartFile upload, Integer width, Integer height,
            @RequestParam("savePath") String savePath, Writer writer) {
        boolean newname = true;
        if (!upload.isEmpty()) {
            
            String uploadFileName = upload.getOriginalFilename();
            if (newname) {
                uploadFileName = Long.toString(System.currentTimeMillis()) + "." + FileUtil.getSuffix(uploadFileName);
            }
            // 自动创建路径
            File path = new File(request.getSession().getServletContext().getRealPath("/") + savePath);
            logger.info("upload path " + path.getAbsolutePath() + " is " + path.exists());
            
            if (!path.exists()) {
                path.mkdirs();
                logger.info("make update path " + path.getAbsolutePath());
            }
            // 确定压缩比例
            if (width == null || height == null) {
                width = 400;
                height = 400;
            }
            
            try {
                ImgUtil.compress(upload.getInputStream(), new FileOutputStream(path.getAbsolutePath() + "/"
                        + uploadFileName), width, height, true, false);
                writer.write("<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction("
                        + CKEditorFuncNum + ",'" + savePath + "/" + uploadFileName + "',''" + ")" + "</script>");
                writer.close();
            }
            catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
            
            logger.info( savePath + "/" + uploadFileName);
            
        }
    }
}
